import { useState, useEffect } from 'react';

/**
 * 窗口尺寸Hook - 获取并监听窗口尺寸变化
 * @returns {{width: number, height: number, isMobile: boolean}} 窗口尺寸信息
 */
export const useWindowSize = () => {
    const [windowSize, setWindowSize] = useState({
        width: typeof window !== 'undefined' ? window.innerWidth : 0,
        height: typeof window !== 'undefined' ? window.innerHeight : 0,
    });

    useEffect(() => {
        if (typeof window === 'undefined') return;

        const handleResize = () => {
            setWindowSize({
                width: window.innerWidth,
                height: window.innerHeight,
            });
        };

        window.addEventListener('resize', handleResize);

        // 立即执行一次获取当前尺寸
        handleResize();

        return () => window.removeEventListener('resize', handleResize);
    }, []);

    return {
        width: windowSize.width,
        height: windowSize.height,
        isMobile: windowSize.width < 768,
        isTablet: windowSize.width >= 768 && windowSize.width < 1024,
        isDesktop: windowSize.width >= 1024,
    };
};

/**
 * 媒体查询Hook - 监听CSS媒体查询变化
 * @param {string} query - 媒体查询字符串
 * @returns {boolean} 是否匹配查询条件
 */
export const useMediaQuery = (query) => {
    const [matches, setMatches] = useState(() => {
        if (typeof window === 'undefined') return false;
        return window.matchMedia(query).matches;
    });

    useEffect(() => {
        if (typeof window === 'undefined') return;

        const mediaQuery = window.matchMedia(query);
        const handleChange = (e) => setMatches(e.matches);

        mediaQuery.addListener(handleChange);
        setMatches(mediaQuery.matches);

        return () => mediaQuery.removeListener(handleChange);
    }, [query]);

    return matches;
};
